
import 'package:get/get.dart';
import 'package:example/config/route_config.dart';
import 'package:example/utils/string_ext.dart';

import '../utils/common.dart';

class WebConfig {
  static final WebConfig _singleton = WebConfig._internal();

  factory WebConfig() {
    return _singleton;
  }

  WebConfig._internal();

  //线上环境
  static const prodUrl = 'https://xxxxxx';

  //测试环境
  static const devUrl = 'https://xxxx';

  static String baseUrl = prodUrl;

  // static const env = {
  //   HttpConfig.prodUrl: prodUrl,
  //   HttpConfig.devUrl: devUrl,
  // };

  /// 生成url
  static String? getUrl(String path, {dynamic params}) {
    if (path.startsWith("http")) {
      return path.addUrlParams(params);
    } else {
      return "$baseUrl$path".addUrlParams(params);
    }
  }

  /// 比较url
  static bool isSameUrl(String url, String? path) {
    if (isEmptyOrNull(path)) {
      return false;
    }
    if (!path!.startsWith(url)) {
      String httpUrl = url.startsWith("http") ? url : baseUrl + url;
      String? httpPath = path.startsWith("http") ? path : baseUrl + path;
      if (!httpPath.startsWith(httpUrl)) {
        String webUrl = url.startsWith("web:") ? url : "web:$url";
        String? webPath = path.startsWith("web:") ? path : "web:$path";
        if (!webPath.startsWith(webUrl)) {
          return false;
        } else {
          url = webUrl;
          path = webPath;
        }
      } else {
        url = httpUrl;
        path = httpPath;
      }
    }
    String last = path.replaceFirst(url, "");
    return isEmptyOrNull(last) || last.startsWith("?");
  }

  /// 跳转方法
  /// path 跳转路径
  /// params 路径参数
  /// arguments 跳转参数
  static Future<T?>? toUrl<T>(String url, {dynamic params, dynamic arguments}) {
    url = url.startsWith("web:") ? url.substring(4) : url;
    url.getUrlParams().forEach((key, value) {
      params ??= {};
      if (params[key] == null) {
        params[key] = value;
      }
    });
    dynamic defArg = {
      "url": getUrl(url.removeUrlParams() ?? "", params: params),
      "isLandscape": false,
      "safeTop": false,
      "safeBottom": true,
      "safeLeft": false,
      "safeRight": false,
    };
    arguments ??= {};
    arguments.forEach((key, value) {
      defArg[key] = value;
    });
    return Get.toNamed<T>(RouteConfig.previewWebView,
        preventDuplicates: false, arguments: defArg);
  }


  // 包含下列便捷跳转方法
  static Future<T?>? toUniversalUrl<T>(String url,
      {dynamic params, dynamic arguments}) {
    return toUrl(url, params: params, arguments: arguments);
  }

}
